package com.tmt.helper;

/**
 * 银行卡辅助类。
 * 作者：ThreeManTeam
 * 创建时间：2019-10-22 12:07
 */
public class BankCardHelper {

    public static boolean checkBankCard(String bankCard) {
        if (bankCard == null || bankCard.trim().length() == 0)
            return false;

        if (bankCard.trim().length() < 15 || bankCard.trim().length() > 19)
            return false;

        char bit = getBankCardCheckCode(bankCard.trim().substring(0, bankCard.trim().length() - 1));
        if (bit == 'N')
            return false;

        return bankCard.trim().charAt(bankCard.trim().length() - 1) == bit;
    }

    public static char getBankCardCheckCode(String noCheckCodeCardNum) {
        if (noCheckCodeCardNum == null || noCheckCodeCardNum.trim().length() == 0
                || !noCheckCodeCardNum.trim().matches("\\d+"))
            return 'N';

        char[] chars = noCheckCodeCardNum.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chars.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chars[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    public static void main(String[] args){
        boolean isOk = BankCardHelper.checkBankCard("6217234402005402227");
        System.out.println(isOk);
    }

}
